//
//  WBEmoticonView.swift
//  SainMicroblog
//
//  Created by chenxinju on 16/5/13.
//  Copyright © 2016年 chenxinju-a2. All rights reserved.
//

import UIKit
//注册cell标识
let WBEmoticonViewReuseIdentifier = "WBEmoticonViewReuseIdentifier"
//删除表情通知名称
let deleButtonNotificationCilck = "deleButtonNotificationCilck"
//点击表情储值到最近表情通知名称
let kNotificationEmoticonTransform = "kNotificationEmoticonTransform"
class WBEmoticonView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        setupCollectionView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupUI() {
        if #available(iOS 9.0, *) {
            addSubview(footerview)
            addSubview(collectionView)
        } else {
            // Fallback on earlier versions
        }
        collectionView.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.top.equalTo(self.snp_top)
            if #available(iOS 9.0, *) {
                make.bottom.equalTo(footerview.snp_top)
            } else {
                // Fallback on earlier versions
            }
        }
        
        if #available(iOS 9.0, *) {
            footerview.snp_makeConstraints { (make) -> Void in
                make.left.equalTo(self.snp_left)
                make.right.equalTo(self.snp_right)
                make.bottom.equalTo(self.snp_bottom)
                make.height.equalTo(44)
            }
        } else {
            // Fallback on earlier versions
        }
    }
    
    private func setupCollectionView() {
        collectionView.delegate = self
        collectionView.dataSource = self
        
        ///  注册cell
        collectionView.registerClass(WBEmoticonViewCell.self, forCellWithReuseIdentifier: WBEmoticonViewReuseIdentifier)
        //分页
        collectionView.pagingEnabled = true
        //隐藏滚动条
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        //弹簧效果关闭
        collectionView.bounces = false
        flowlayout.itemSize = collectionView.frame.size
        flowlayout.minimumInteritemSpacing = 0
        flowlayout.minimumLineSpacing = 0
        //设置左右滚动 流水布局
        flowlayout.scrollDirection = .Horizontal
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        //print(collectionView.frame.size)
        flowlayout.itemSize = collectionView.frame.size
        
    }
    
    
    //    MARK: - 懒加载控件
    @available(iOS 9.0, *)
    private lazy var footerview: WBEmoticonStatckView = {
        
        let footer = WBEmoticonStatckView(frame: CGRectZero)
        
        footer.delegate = self
        
        return footer
        
    }()
    
    private var flowlayout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.flowlayout)
    
    
}
//MARK: - EmoticonStatckViewDelegate
extension WBEmoticonView: EmoticonStatckViewDelegate {
    
    func didEmoticonSelectedSecion(type: EmoticonStatckType) {
        
        switch type {
            
        case .Recent:
            let index = NSIndexPath(forRow: 0, inSection: 0)
            collectionView.scrollToItemAtIndexPath(index, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
            
        case .Default:
            let index = NSIndexPath(forRow: 0, inSection: 1)
            collectionView.scrollToItemAtIndexPath(index, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        case .Emoji:
            let index = NSIndexPath(forRow: 0, inSection: 2)
            collectionView.scrollToItemAtIndexPath(index, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        case .Lxh:
            let index = NSIndexPath(forRow: 0, inSection: 3)
            collectionView.scrollToItemAtIndexPath(index, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        }
        
    }
}

extension WBEmoticonView: UICollectionViewDataSource,UICollectionViewDelegate {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return WBEmoticonManager.getAllEmoticon().count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return WBEmoticonManager.getAllEmoticon()[section].count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell =  collectionView.dequeueReusableCellWithReuseIdentifier(WBEmoticonViewReuseIdentifier, forIndexPath: indexPath) as! WBEmoticonViewCell
        
        cell.emotions = WBEmoticonManager.getAllEmoticon()[indexPath.section][indexPath.row]
        
        return cell
    }
    
    /// UIScrollView滚动时触发
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        let visible = collectionView.visibleCells()
          printLog(visible.count)
        if visible.count == 2 {
            //计算占位比较多
            let firstsCell = visible.first!
            let lastCell = visible.last!
            
            let firstMargin = abs(scrollView.contentOffset.x - firstsCell.frame.origin.x)
            let lastMargin = abs(scrollView.contentOffset.x - lastCell.frame.origin.x)
            
            //printLog("first\(firstMargin)")
            //printLog("last\(lastMargin)")
            
            if firstMargin < lastMargin {
                //显示firstMargin 所对应的secion
                let index = collectionView.indexPathForCell(firstsCell)!
                if #available(iOS 9.0, *) {
//                    printLog(index.section)
                    footerview.showSelectedButton((index.section))
                } else {
                    // Fallback on earlier versions
                    if #available(iOS 9.0, *) {
                        let index = collectionView.indexPathForCell(lastCell)!
//                        printLog(index.section)
                        footerview.showSelectedButton(index.section)
                    } else {
                        // Fallback on earlier versions
                    }
                    
                }
                
            }
            
        }
        
        
    }
    
}

//MARK: - 自定义cell
class WBEmoticonViewCell: UICollectionViewCell {
    
    //定义一个表情数组 用于传值
    var emotions: [WBEmoticon]? {
        
        didSet {
            //print(emotions?.count)
            //遍历数组内所有buttons
            for button in buttons {
                button.hidden = true
            }
            //获取到表情的model 根据model 数据来显示表情
            for (index,emoticon) in emotions!.enumerate() {
                // print("\(emoticon.package)/\(emoticon.png)")
                let button = buttons[index]
                button.emoticon = emoticon
                button.hidden = false
            }
        }
    }
    

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private  func setupUI() {
        backgroundColor = RandomColor()
        addCildButtons()
        
    }
    
    //添加用于显示表情的按钮
    private func addCildButtons() {
        let childButtonWidth = self.bounds.width / CGFloat(WBEmoticonCol)
        let childButtonHeight = self.bounds.height / CGFloat(WBEmoticonRow)
        
        for i in 0..<WBEmoticonNum {
            //自定义button
            let button = WBEmoticonButton(type: UIButtonType.Custom)
            //设置属性
            button.addTarget(self, action: "emoticonButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            //设置属性
            button.titleLabel?.font = UIFont.systemFontOfSize(36)
            let col = i % WBEmoticonCol
            let row = i / WBEmoticonCol
            
            //frame
            button.frame.size = CGSizeMake(childButtonWidth, childButtonHeight)
            button.frame.origin.x = childButtonWidth * CGFloat(col)
            button.frame.origin.y = childButtonHeight * CGFloat(row)
            //添加到数组中
            buttons.append(button)
            contentView.addSubview(button)
        }
        //删除图片按钮
        delebutton.frame.size = CGSizeMake(childButtonWidth, childButtonHeight)
        delebutton.frame.origin.x = self.bounds.width - childButtonWidth
        delebutton.frame.origin.y = self.bounds.height - childButtonHeight
        contentView.addSubview(delebutton)
    }
    
    
    
    //    MARK: - 点击表情的方法
    //把按钮的点击保存传递到 最近cell中显示
    @objc private func emoticonButtonClick(button:WBEmoticonButton) {
        
        if  let emoticon = button.emoticon {
            
            NSNotificationCenter.defaultCenter().postNotificationName(kNotificationEmoticonTransform, object: self, userInfo: ["key":emoticon])
            //通过调用方法 添加表情
            WBEmoticonManager.addRecent(emoticon)
            
        }
    }
    ///  点击表情框删除按钮
    @objc private func deleButtonCilck(button:WBEmoticonButton) {
        
        NSNotificationCenter.defaultCenter().postNotificationName(deleButtonNotificationCilck, object: ["key":"value"])
    }
    
    //    MARK:- 懒加载
    //测试label
    //定义一个数组来 装 buttons
    private lazy var buttons: [WBEmoticonButton] = [WBEmoticonButton]()
    private lazy var delebutton: UIButton = {
        let button = UIButton(type: UIButtonType.Custom)
        button.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
        //点击方法
        button.addTarget(self, action: "deleButtonCilck:", forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()
    
}
